package com.zhang.family_doctor.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.WriterException;
import com.zhang.family_doctor.dto.TeamDto;
import com.zhang.family_doctor.entity.*;
import com.zhang.family_doctor.mapper.*;
import com.zhang.family_doctor.service.TeamService;
import com.zhang.family_doctor.utils.CommonUtils;
import com.zhang.family_doctor.utils.QRCodeGenerator;
import com.zhang.family_doctor.utils.TokenUtils;
import com.zhang.family_doctor.vo.TeamIJoinedVO;
import com.zhang.family_doctor.vo.TeamManageVO;
import com.zhang.family_doctor.vo.TeamPackagesVO;
import com.zhang.family_doctor.vo.TeamVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class TeamServiceImpl implements TeamService {

    @Autowired
    private TeamTagMapper teamTagMapper;

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private TeamPackagesMapper teamPackagesMapper;

    @Autowired
    private TeamJoinedMapper teamJoinedMapper;

    @Autowired
    private ApplyJoinTeamMapper applyJoinTeamMapper;

    @Value("${family_doctor.path}")
    private String url;

    @Value("${suffix}")
    private String suffix;

    /**
     * 新增医生团队
     *
     * @param teamDto
     * @param request
     * @return
     */
    @Override
    @Transactional
    public R<String> save(TeamDto teamDto, HttpServletRequest request) throws IOException, WriterException {

        String tokenBackstage = request.getHeader("tokenBackstage");
        String getName = TokenUtils.verifyAndGetName(tokenBackstage);
        Integer doctorId = Integer.valueOf(TokenUtils.verifyAndGetDoctorId(tokenBackstage));

        int id = CommonUtils.genUUID();

        teamDto.setId(id);
        teamDto.setTeamNumber(CommonUtils.genUUID());
        teamDto.setDoctorId(doctorId);
        teamDto.setTeamLeader(getName);
        //新增默认启用状态
        teamDto.setState(1);
        teamDto.setCreateTime(new Date());
        teamDto.setUpdateTime(new Date());

        //生成团队二维码
        String path = url + teamDto.getId() + suffix;
        teamDto.setMinePlease(path);
        teamMapper.save(teamDto);

        QRCodeGenerator.generateQRCodeImage(String.valueOf(teamDto.getId()), 350, 350, path);

        //团队标签
        List<TeamTag> teamTagList = teamDto.getTeamTagList();
        for (TeamTag teamTag : teamTagList) {
            teamTag.setId(CommonUtils.genUUID());
            teamTag.setTeamId(id);
        }
        teamTagMapper.save(teamTagList);
        //团队服务包关联表
        List<TeamPackages> teamPackagesList = teamDto.getTeamPackagesList();
        for (TeamPackages teamPackages : teamPackagesList) {
            teamPackages.setId(CommonUtils.genUUID());
            teamPackages.setTeamId(id);
        }
        teamPackagesMapper.save(teamPackagesList);

        //我加入的团队
        TeamJoined teamJoined = new TeamJoined();
        teamJoined.setId(CommonUtils.genUUID());
        teamJoined.setTeamId(id);
        teamJoined.setDoctorId(doctorId);
        teamJoined.setCreateTime(new Date());
        teamJoined.setTeamLeader(1);

        teamJoinedMapper.save(teamJoined);

        return R.success("新增团队成功！");
    }

    /**
     * 编辑团队
     *
     * @param teamDto
     * @return
     */
    @Override
    @Transactional
    public R<String> updateTeam(TeamDto teamDto) {
        Integer id = teamDto.getId();

        teamDto.setUpdateTime(new Date());
        teamMapper.updateTeam(teamDto);

        teamTagMapper.delete(id);
        List<TeamTag> teamTagList = teamDto.getTeamTagList();
        for (TeamTag teamTag : teamTagList) {
            teamTag.setId(CommonUtils.genUUID());
            teamTag.setTeamId(id);
        }
        teamTagMapper.save(teamTagList);

        return R.success("编辑成功！");
    }

    /**
     * 给团队添加服务包
     *
     * @param teamDto
     * @return
     */
    @Override
    public R<String> savePackages(TeamDto teamDto) {
        Integer id = teamDto.getId();
        List<TeamPackages> teamPackagesList = teamDto.getTeamPackagesList();
        for (TeamPackages teamPackages : teamPackagesList) {
            teamPackages.setId(CommonUtils.genUUID());
            teamPackages.setTeamId(id);
        }
        teamPackagesMapper.save(teamPackagesList);
        return R.success("添加服务包成功！");
    }

    /**
     * 启用或禁用团队
     *
     * @param team
     * @return
     */
    @Override
    public R<String> enableOrDisable(Team team) {

        team.setUpdateTime(new Date());

        Integer state = team.getState();

        if (state == 1) {
            teamMapper.enableOrDisable(team);
            return R.success("启用成功！");
        } else if (state == 2) {
            teamMapper.enableOrDisable(team);
            return R.success("禁用成功！");
        }

        return R.buildFailure("操作失败！");
    }

    /**
     * 解散团队
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public R<String> dissolutionTeam(Integer id) {

        //清除掉团队标签表数据
        teamTagMapper.delete(id);
        //清除掉我加入的团队
        teamJoinedMapper.delete(id);
        //清除掉团队服务包
        teamPackagesMapper.delete(id);
        //删除团队
        teamMapper.delete(id);

        return R.success("团队解散成功！");
    }

    /**
     * 申请加入团队
     *
     * @param applyJoinTeam
     * @param request
     * @return
     */
    @Override
    public R<String> applyToJoinTeam(ApplyJoinTeam applyJoinTeam, HttpServletRequest request) {

        String tokenBackstage = request.getHeader("tokenBackstage");
        Integer doctorId = Integer.valueOf(TokenUtils.verifyAndGetDoctorId(tokenBackstage));
        Integer teamId = applyJoinTeam.getTeamId();


        ApplyJoinTeam joinTeamByDoctorIdAndTeamIdOne = applyJoinTeamMapper.getApplyJoinTeamByDoctorIdAndTeamIdOne(doctorId, teamId);

        //给拒绝可以再发申请
        if (joinTeamByDoctorIdAndTeamIdOne != null){
            return R.buildFailure("申请失败！已经申请或者已经通过了！");
        }
        ApplyJoinTeam joinTeamByDoctorIdAndTeamIdTwo = applyJoinTeamMapper.getApplyJoinTeamByDoctorIdAndTeamIdTwo(doctorId, teamId);
        if(joinTeamByDoctorIdAndTeamIdTwo != null){
            applyJoinTeamMapper.delete(doctorId,teamId);
        }
        ApplyJoinTeam joinTeamByDoctorIdAndTeamIdThree = applyJoinTeamMapper.getApplyJoinTeamByDoctorIdAndTeamIdThree(doctorId, teamId);
        if (joinTeamByDoctorIdAndTeamIdThree != null){
            applyJoinTeamMapper.delete(doctorId,teamId);
        }

        applyJoinTeam.setId(CommonUtils.genUUID());
        applyJoinTeam.setCreateTime(new Date());
        applyJoinTeam.setDoctorId(doctorId);
        //默认待审核状态
        applyJoinTeam.setAuditStatus(1);

        applyJoinTeamMapper.applyToJoinTeam(applyJoinTeam);

        return R.success("申请成功！");
    }

    /**
     * 通过或者拒绝
     * @param applyJoinTeam
     * @return
     */
    @Override
    @Transactional
    public R<String> passOrReject(ApplyJoinTeam applyJoinTeam) {

        TeamJoined teamJoined = new TeamJoined();
        Integer auditStatus = applyJoinTeam.getAuditStatus();
        Integer teamId = applyJoinTeam.getTeamId();
        Integer doctorId = applyJoinTeam.getDoctorId();
        if (auditStatus == 2) {
            //修改申请表中的状态
            applyJoinTeamMapper.updateById(applyJoinTeam);

            //通过的同时往我加入的团队插入一条数据
            teamJoined.setId(CommonUtils.genUUID());
            teamJoined.setTeamId(teamId);
            teamJoined.setDoctorId(doctorId);
            teamJoined.setCreateTime(new Date());
            //职务为成员
            teamJoined.setTeamLeader(2);
            TeamJoined selectTeamJoinByTeamIdAndDoctorId = teamJoinedMapper.selectTeamJoinByTeamIdAndDoctorId(teamJoined);
            if (selectTeamJoinByTeamIdAndDoctorId != null){
                return R.buildFailure("已经通过了");
            }
            teamJoinedMapper.save(teamJoined);
            return R.success("通过成功！");
        } else if (auditStatus == 3) {
            //修改申请表中的状态
            applyJoinTeamMapper.updateById(applyJoinTeam);
            return R.success("拒绝成功！");
        }
        return R.buildFailure("操作失败");
    }

    /**
     * 团队成员退出团队
     * @param id
     * @return
     */
    @Override
    @Transactional
    public R<String> signOutTeam(Integer id) {

        TeamJoined teamJoined = teamJoinedMapper.selectTeamJoinById(id);
        if (teamJoined == null){
            return R.buildFailure("没有该数据");
        }
        Integer teamId = teamJoined.getTeamId();
        Integer doctorId = teamJoined.getDoctorId();

        applyJoinTeamMapper.updateByTeamIdAndDoctorId(teamId,doctorId);

        teamJoinedMapper.deleteTeamJoinById(id);

        return R.success("操作成功！");
    }

    /**
     * 分页查询我管理的团队
     * @param pageNum
     * @param pageSize
     * @param request
     * @return
     */
    @Override
    public R<PageInfo<TeamVO>> getTeam(Integer pageNum, Integer pageSize,Integer mechanismId,String teamName, HttpServletRequest request) {

        String tokenBackstage = request.getHeader("tokenBackstage");
        Integer doctorId = Integer.valueOf(TokenUtils.verifyAndGetDoctorId(tokenBackstage));
        PageHelper.startPage(pageNum, pageSize);
        List<TeamVO> teamList = teamMapper.getTeam(doctorId,mechanismId,teamName);
        for (TeamVO teamVO : teamList){
            Integer id = teamVO.getId();
            List<String> teamTagByTeamId = teamTagMapper.getTeamTagByTeamId(id);
            teamVO.setTeamTagNameList(teamTagByTeamId);
        }
        PageInfo<TeamVO> teamPageInfo = new PageInfo<>(teamList);

        return R.success(teamPageInfo);
    }

    /**
     * 分页查询我加入的团队
     * @param pageNum
     * @param pageSize
     * @param request
     * @return
     */
    @Override
    public R<PageInfo<TeamVO>> getTeamJoined(Integer pageNum, Integer pageSize,Integer mechanismId,String teamName, HttpServletRequest request) {

        String tokenBackstage = request.getHeader("tokenBackstage");
        Integer doctorId = Integer.valueOf(TokenUtils.verifyAndGetDoctorId(tokenBackstage));
        PageHelper.startPage(pageNum, pageSize);
        List<TeamVO> teamJoined = teamMapper.getTeamJoined(doctorId,mechanismId,teamName);
        for (TeamVO teamVO : teamJoined){
            Integer id = teamVO.getId();
            List<String> teamTagByTeamId = teamTagMapper.getTeamTagByTeamId(id);
            teamVO.setTeamTagNameList(teamTagByTeamId);
        }
        PageInfo<TeamVO> teamPageInfo = new PageInfo<>(teamJoined);

        return R.success(teamPageInfo);
    }

    /**
     * 查看我管理的团队详情
     * @param id
     * @return
     */
    @Override
    public R<TeamManageVO> getTeamManageDetails(Integer id) {

        TeamManageVO teamManageVO = new TeamManageVO();
        //查询出团队
        Team team = teamMapper.selectTeamById(id);
        //查询出团队标签
        List<String> teamTagByTeamId = teamTagMapper.getTeamTagByTeamId(id);
        //服务包和服务包标签
        TeamPackagesVO teamPackagesVO = new TeamPackagesVO();
        List<TeamPackages> teamPackagesList = teamPackagesMapper.selectTeamPackagesByTeamId(id);
        for (TeamPackages teamPackages : teamPackagesList){
            Integer packagesId = teamPackages.getPackagesId();
            List<Packages> packagesList = teamPackagesMapper.selectPackagesById(packagesId);
            List<String> selectTeamPackagesTagNameList = teamPackagesMapper.selectTeamPackagesTagNameList(id, packagesId);
            teamPackagesVO.setPackagesList(packagesList);
            teamPackagesVO.setTeamPackagesTagNameList(selectTeamPackagesTagNameList);
        }
        //团队成员
        List<Doctor> teamMembers = teamJoinedMapper.selectTeamJoinByTeamId(id);
        //申请团队医生
        List<Doctor> joiningTeam = applyJoinTeamMapper.selectApplyJoinTeamByTeamId(id);
        teamManageVO.setTeam(team);
        teamManageVO.setTeamTagNameList(teamTagByTeamId);
        teamManageVO.setTeamPackagesVO(teamPackagesVO);
        teamManageVO.setTeamMembers(teamMembers);
        teamManageVO.setJoiningTeam(joiningTeam);

        return R.success(teamManageVO);
    }

    /**
     * 查看我加入的团队详情
     * @param id 团队id
     * @return
     */
    @Override
    public R<TeamIJoinedVO> getTeamIJoinedDetails(Integer id) {

        TeamIJoinedVO teamIJoinedVO = new TeamIJoinedVO();
        //查询出团队
        Team team = teamMapper.selectTeamById(id);
        //查询出团队标签
        List<String> teamTagByTeamId = teamTagMapper.getTeamTagByTeamId(id);
        //服务包和服务包标签
        TeamPackagesVO teamPackagesVO = new TeamPackagesVO();
        List<TeamPackages> teamPackagesList = teamPackagesMapper.selectTeamPackagesByTeamId(id);
        for (TeamPackages teamPackages : teamPackagesList){
            Integer packagesId = teamPackages.getPackagesId();
            List<Packages> packagesList = teamPackagesMapper.selectPackagesById(packagesId);
            List<String> selectTeamPackagesTagNameList = teamPackagesMapper.selectTeamPackagesTagNameList(id, packagesId);
            teamPackagesVO.setPackagesList(packagesList);
            teamPackagesVO.setTeamPackagesTagNameList(selectTeamPackagesTagNameList);
        }
        //团队成员
        List<Doctor> teamMembers = teamJoinedMapper.selectTeamJoinByTeamId(id);

        teamIJoinedVO.setTeam(team);
        teamIJoinedVO.setTeamTagNameList(teamTagByTeamId);
        teamIJoinedVO.setTeamPackagesVO(teamPackagesVO);
        teamIJoinedVO.setTeamMembers(teamMembers);

        return R.success(teamIJoinedVO);
    }

    /**
     * 根据机构id查询团团队
     * @param mechanismId
     * @return
     */
    @Override
    public R<List<Team>> getTeamByMechanismId(Integer mechanismId) {

        List<Team> teamByMechanismId = teamMapper.getTeamByMechanismId(mechanismId);

        return R.success(teamByMechanismId);
    }

    /**
     * 根据团队id查询队员
     * @param teamId
     * @return
     */
    @Override
    public R<List<TeamJoined>> getTeamJoinedByTeamId(Integer teamId) {

        List<TeamJoined> teamJoinedByTeamId = teamJoinedMapper.getTeamJoinedByTeamId(teamId);

        return R.success(teamJoinedByTeamId);
    }

}
